package com.sailfish.springbootdemo.service.db5;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.dao.db2.AxiConfigDao;
import com.sailfish.springbootdemo.dao.db2.BoardProportionInfoDao;
import com.sailfish.springbootdemo.dao.db2.PcbParentFactoryInfoDao;
import com.sailfish.springbootdemo.dao.db5.BoardProportionDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.EmailRecord;
import com.sailfish.springbootdemo.pojo.db2.AxiConfig;
import com.sailfish.springbootdemo.pojo.db2.BoardProportionInfo;
import com.sailfish.springbootdemo.pojo.db2.PcbParentFactoryInfo;
import com.sailfish.springbootdemo.pojo.db5.BoardCompanyData;
import com.sailfish.springbootdemo.pojo.db5.BoardFactoryInfo;
import com.sailfish.springbootdemo.pojo.db5.BoardProportion;
import com.sailfish.springbootdemo.pojo.db5.BoardResult;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.HttpUtil;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BoardProportionServiceImpl implements BoardProportionService {

    @Autowired
    private BoardProportionDao boardProportionDao;
    @Autowired
    private PcbParentFactoryInfoDao pcbParentFactoryInfoDao;
    @Autowired
    private AxiConfigDao axiConfigDao;
    @Autowired
    private BoardProportionInfoDao boardProportionInfoDao;

    @Value("${personal.config.httpUrl.getBoardList}")
    String getBoardListApi;

    @Override
    public List<AxiConfig> getAxiConfigList() {
        final List<AxiConfig> listByLimit = axiConfigDao.getListByLimit(null, 3);
        return listByLimit;
    }

    @Override
    public Result updateAxiConfig(String data) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(data);
            if (jsonArray == null || jsonArray.size() == 0) {
                return ResultUtil.error(500, "参数为空", "param is null", null);
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                final Integer id = jsonObject.getInteger("id");
                final JSONArray attrValueArr = jsonObject.getJSONArray("attrValue");
                if (id == null || attrValueArr == null || attrValueArr.size() == 0) {
                    return ResultUtil.error(500, "参数id或者attrValue为空", "param is null", null);
                }
                String attrValue = "";
                for (int j = 0; j < attrValueArr.size(); j++) {
                    final Object obj = attrValueArr.get(j);
                    attrValue += obj.toString() + ",";
                }
                if (attrValue.length() > 0) {
                    attrValue = attrValue.substring(0, attrValue.length() - 1);
                }
                AxiConfig axiConfig = new AxiConfig();
                axiConfig.setId(id);
                axiConfig.setAttrValue(attrValue);
                axiConfig.setUpdateTime(new Date());
                axiConfigDao.update(axiConfig);
            }
            return ResultUtil.success(null);

        } catch (Exception e) {
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }


    @Override
    public Result getBoarProportion() {
        try {
            System.out.println("111");
            AxiConfig timeRange = axiConfigDao.getByAttrName("BoarProportion_TimeRange", 3);
            AxiConfig layerTypes = axiConfigDao.getByAttrName("BoarProportion_LayerTypes", 3);
            if (timeRange == null || layerTypes == null) {
                return ResultUtil.error(500, "时间范围或者层数类型未定义", null, null);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (StringUtils.isBlank(timeRange.getAttrValue()) || StringUtils.isBlank(layerTypes.getAttrValue())) {
                return ResultUtil.error(500, "时间范围或者层数类型数据未定义", null, null);
            }
            System.out.println("timeRange:" + JSONObject.toJSONString(timeRange));
            System.out.println("layerTypes:" + JSONObject.toJSONString(layerTypes));
            String[] timeRangeArr = timeRange.getAttrValue().split(",");
            String[] layerTypesArr = layerTypes.getAttrValue().split(",");
            Date startTime = null;
            Date endTime = null;
            if (timeRangeArr != null && timeRangeArr.length > 0) {
                startTime = sdf.parse(timeRangeArr[0]);
                endTime = sdf.parse(timeRangeArr[1]);
            }
            System.out.println("222");
            PcbParentFactoryInfo search = new PcbParentFactoryInfo();
            search.setStatus(1);
            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoDao.getAllByLimit(search);
            System.out.println("333");
            List<BoardProportion> list = boardProportionDao.getList(startTime, endTime, null,1,1000);
            System.out.println("444");
            if (list != null) {
                System.out.println("list.size():" + list.size());
            }
            String md5Sign = "6244832a706bbb2c81fb093367027f56";
            MultipartEntityBuilder params = MultipartEntityBuilder.create();
            params.addTextBody("signature", md5Sign);
            String res = HttpUtil.sendPostFormData(getBoardListApi, params);
            JSONObject jsonObjectRes = JSON.parseObject(res);//
            Map<String, Integer> map = new HashMap<>();
            if (jsonObjectRes.getInteger("code") == 200) {
                JSONArray jsonArray = jsonObjectRes.getJSONArray("data");
                if(jsonArray!=null){
                    System.out.println("data size:"+jsonArray.size());
                }
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    JSONArray boardParamValueList = jo.getJSONArray("boardParamValueList");
                    Integer projectId = jo.getInteger("projectId");
                    Integer layers = null;
                    String productCode0301 = jo.getString("projectCode0301") == null ? "" : jo.getString("projectCode0301");
                    String productVersion = jo.getString("projectVersion") == null ? "" : jo.getString("projectVersion");//VA

                    if (boardParamValueList == null || StringUtils.isBlank(productCode0301) || StringUtils.isBlank(productVersion)) {
                        continue;
                    }
//                    System.out.println("t boardParamValueList.size() :" + boardParamValueList.size());
                    for (int j = 0; j < boardParamValueList.size(); j++) {
                        JSONObject jo2 = boardParamValueList.getJSONObject(j);
                        String boardParamKey = jo2.getString("boardParamKey");
                        String paramValue = jo2.getString("boardParamValue");
                        if (boardParamKey.equals("board_layer_qty") && !StringUtils.isBlank(paramValue)) {
                            layers = Integer.parseInt(paramValue);//productCode0301,productVersion
                            break;
                        }
                    }
                    String key = productCode0301 + "-VER." + productVersion;
                    if (!map.containsKey(key)) {
                        map.put(key, layers);
                    }
                }
            } else {
                return ResultUtil.error(500, "send request error:" + jsonObjectRes.getString("msgCn"), null, null);
            }

            List<BoardResult> results = new ArrayList<>();

            Map<String, Object> mapRes = new HashMap<>();
            mapRes.put("timeRange", timeRangeArr);
            mapRes.put("layerTypes", layerTypesArr);
            if (layerTypesArr != null) {
                List<BoardCompanyData> dataList = new ArrayList<>();
                for (int i = 0; i < layerTypesArr.length; i++) {
                    BoardCompanyData boardCompanyData = new BoardCompanyData();
                    String layerType = layerTypesArr[i].trim();
                    Integer sumLayer = 0;
                    Map<String, Integer> factoryMap = new HashMap<>();
                    for (int m = 0; m < list.size(); m++) {
                        Integer layerB = StringUtils.isBlank(list.get(m).getNh3cLayersNo()) ? 0 : Integer.parseInt(list.get(m).getNh3cLayersNo());
                        String code0301 = list.get(m).getNh3cPrintbocoding().trim().toUpperCase();
                        String boardVer = list.get(m).getNh3cPcbrevision().trim().toUpperCase();
                        String bpm_factoryName = list.get(m).getNh3cForeignassman()==null ? "" : list.get(m).getNh3cForeignassman().trim();
                        String keyB = code0301 + "-" + boardVer;
                        if (map.containsKey(keyB) && map.get(keyB)!=null && map.get(keyB)!=0) {
                            layerB = map.get(keyB);
                        }
                        if (layerType.contains("~")) {
                            if (layerType.indexOf("~") == layerType.length() - 1) //20~
                            {
                                Integer layer = Integer.parseInt(layerType.substring(0, layerType.length() - 1));
                                if (layerB >= layer) {
                                    sumLayer++;
                                }
                                for (int j = 0; j < pcbParentFactoryInfoList.size(); j++) {
                                    String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
                                    if (layerB >= layer) {
                                        if (factoryName.equals(bpm_factoryName)) {
                                            if (factoryMap.containsKey(factoryName)) {
                                                Integer qty = factoryMap.get(factoryName) + 1;
                                                factoryMap.put(factoryName, qty);
                                            } else {
                                                factoryMap.put(factoryName, 1);
                                            }
                                        } else {
                                            if (!factoryMap.containsKey(factoryName)) {
                                                factoryMap.put(factoryName, 0);
                                            }
                                        }
                                    }
                                }
                            } else if (layerType.indexOf("~") == 0) {
                                Integer layer = Integer.parseInt(layerType.substring(0, layerType.length() - 1));
                                if (layerB <= layer) {
                                    sumLayer++;
                                }
                                for (int j = 0; j < pcbParentFactoryInfoList.size(); j++) {
                                    String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
                                    if (layerB <= layer) {
                                        if (factoryName.equals(bpm_factoryName)) {
                                            if (factoryMap.containsKey(factoryName)) {
                                                Integer qty = factoryMap.get(factoryName) + 1;
                                                factoryMap.put(factoryName, qty);
                                            } else {
                                                factoryMap.put(factoryName, 1);
                                            }
                                        } else {
                                            if (!factoryMap.containsKey(factoryName)) {
                                                factoryMap.put(factoryName, 0);
                                            }
                                        }
                                    }
                                }
                            } else {//2~10,14~18
                                Integer layer1 = Integer.parseInt(layerType.substring(0, layerType.indexOf("~")));
                                Integer layer2 = Integer.parseInt(layerType.substring(layerType.indexOf("~") + 1));
                                if (layerB >= layer1 && layerB <= layer2) {
                                    sumLayer++;
                                }
                                for (int j = 0; j < pcbParentFactoryInfoList.size(); j++) {
                                    String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
                                    if (layerB >= layer1 && layerB <= layer2) {
                                        if (factoryName.equals(bpm_factoryName)) {
                                            if (factoryMap.containsKey(factoryName)) {
                                                Integer qty = factoryMap.get(factoryName) + 1;
                                                factoryMap.put(factoryName, qty);
                                            } else {
                                                factoryMap.put(factoryName, 1);
                                            }
                                        } else {
                                            if (!factoryMap.containsKey(factoryName)) {
                                                factoryMap.put(factoryName, 0);
                                            }
                                        }
                                    }
                                }
                            }
                        } else { //12
                            Integer layer = Integer.parseInt(layerType);
                            if (layer == layerB) {
                                sumLayer++;

                            }
                            for (int j = 0; j < pcbParentFactoryInfoList.size(); j++) {
                                String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
                                if (layer == layerB) {
                                    if (factoryName.equals(bpm_factoryName)) {
                                        if (factoryMap.containsKey(factoryName)) {
                                            Integer qty = factoryMap.get(factoryName) + 1;
                                            factoryMap.put(factoryName, qty);
                                        } else {
                                            factoryMap.put(factoryName, 1);
                                        }
                                    } else {
                                        if (!factoryMap.containsKey(factoryName)) {
                                            factoryMap.put(factoryName, 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    boardCompanyData.setCompanyDataList(factoryMap);
                    boardCompanyData.setLayerType(layerType);
                    boardCompanyData.setSumQty(sumLayer);
                    dataList.add(boardCompanyData);
                }

                for (int i = 0; i < dataList.size(); i++) {
                    BoardResult boardResult = new BoardResult();
                    boardResult.setLayerType(dataList.get(i).getLayerType() + "层");

                    Integer sumQty = dataList.get(i).getSumQty();
                    Map<String, Integer> companyDataList = dataList.get(i).getCompanyDataList();
                    List<BoardResult.CompanyData> companyList = new ArrayList<>();
                    for (Map.Entry<String, Integer> entry : companyDataList.entrySet()) {
                        BoardResult.CompanyData companyData = new BoardResult.CompanyData();
                        List<PcbParentFactoryInfo> collect = pcbParentFactoryInfoList.stream().filter(x -> x.getCompanyNameFull().equals(entry.getKey())).collect(Collectors.toList());
                        if (collect.size() > 0) {
                            companyData.setCompanyCode(collect.get(0).getCompanyCode());
                            companyData.setCompanyName(collect.get(0).getCompanyName());
                            companyData.setCompanyNameFull(entry.getKey());
                            final double v = entry.getValue() * 1.0 / sumQty;
                            double number = sumQty == 0 ? 0 : ((entry.getValue() * 1.0 / sumQty) * 100);
                            DecimalFormat df = new DecimalFormat("#.00");
                            String formattedNumber = df.format(number);
                            double result = Double.parseDouble(formattedNumber);
                            companyData.setProportionValue(result + "%");
                        }
                        companyList.add(companyData);
                    }
                    boardResult.setCompanyList(companyList);
                    results.add(boardResult);
                }
            }
            mapRes.put("data", results);
            return ResultUtil.success(mapRes);
        } catch (Exception e) {
            return ResultUtil.error(500, "异常:" + e.getMessage(), "Exception:" + e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result getBoardTableInfo(Integer page, Integer pageSize) {
        try {
            System.out.println("t111");
            AxiConfig timeRange = axiConfigDao.getByAttrName("BoarProportion_TimeRange", 3);
            AxiConfig layerTypes = axiConfigDao.getByAttrName("BoarProportion_LayerTypes", 3);
            if (timeRange == null || layerTypes == null) {
                return ResultUtil.error(500, "时间范围或者层数类型未定义", null, null);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (StringUtils.isBlank(timeRange.getAttrValue()) || StringUtils.isBlank(layerTypes.getAttrValue())) {
                return ResultUtil.error(500, "时间范围或者层数类型数据未定义", null, null);
            }
            String[] timeRangeArr = timeRange.getAttrValue().split(",");
            String[] layerTypesArr = layerTypes.getAttrValue().split(",");
            System.out.println("t222");
            Date startTime = null;
            Date endTime = null;
            if (timeRangeArr != null && timeRangeArr.length > 1) {
                startTime = sdf.parse(timeRangeArr[0]);
                endTime = sdf.parse(timeRangeArr[1]);
            }
            System.out.println("t444");
            if (page == null || !CommonUtils.isNumeric(page.toString())) {
                return ResultUtil.error(500, "错误参数page", "Error Param page", null);
            }
            if (pageSize == null || !CommonUtils.isNumeric(pageSize.toString())) {
                return ResultUtil.error(500, "错误参数pageSize", "Error Param pageSize", null);
            }
            int begin = (page - 1) * pageSize;
            List<BoardProportion> list = boardProportionDao.getList(startTime, endTime, null,begin,pageSize);
            List<BoardProportion> list2 = boardProportionDao.getList(startTime, endTime, null,null,null);
            if (list != null) {
                System.out.println("t list.size():" + list.size());
            }
            System.out.println("t555");
            String md5Sign = "6244832a706bbb2c81fb093367027f56";
            MultipartEntityBuilder params = MultipartEntityBuilder.create();
            params.addTextBody("signature", md5Sign);
            String res = HttpUtil.sendPostFormData(getBoardListApi, params);
            System.out.println("t getBoardListApi:" + getBoardListApi);
//            System.out.println("t sendPostFormData res:"+res);
            JSONObject jsonObjectRes = JSON.parseObject(res);
            Map<String, Integer> map = new HashMap<>();
            Map<String, String> map2 = new HashMap<>();
            if (jsonObjectRes.getInteger("code") == 200) {
                JSONArray jsonArray = jsonObjectRes.getJSONArray("data");
                if(jsonArray!=null){
                    System.out.println("t data size:"+jsonArray.size());
                }
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    JSONArray boardParamValueList = jo.getJSONArray("boardParamValueList");
                    Integer layers = null;
                    String productCode0301 = jo.getString("projectCode0301") == null ? "" : jo.getString("projectCode0301");
                    String productVersion = jo.getString("projectVersion") == null ? "" : jo.getString("projectVersion");//VA
                    String productBoardName = "";
                    if (boardParamValueList == null || StringUtils.isBlank(productCode0301) || StringUtils.isBlank(productVersion)) {
                        continue;
                    }
//                    System.out.println("t boardParamValueList.size() :" + boardParamValueList.size());
                    for (int j = 0; j < boardParamValueList.size(); j++) {
                        JSONObject jo2 = boardParamValueList.getJSONObject(j);
                        String boardParamKey = jo2.getString("boardParamKey");
                        String paramValue = jo2.getString("boardParamValue");
                        if (boardParamKey.equals("board_layer_qty") && !StringUtils.isBlank(paramValue)) {
                            layers = Integer.parseInt(paramValue);//productCode0301,productVersion
                        }
                        if (boardParamKey.equals("productBoardName") && !StringUtils.isBlank(paramValue)) {
                            productBoardName = paramValue;//productCode0301,productVersion
                        }
                    }

                    String key = productCode0301 + "-VER." + productVersion;
                    if (!map.containsKey(key)) {
                        map.put(key, layers);
                    }
                    if (!map2.containsKey(key)) {
                        map2.put(key, productBoardName);
                    }
                }
            } else {
                return ResultUtil.error(500, "send request error:" + jsonObjectRes.getString("msgCn"), null, null);
            }
            System.out.println("t777");
            List<BoardFactoryInfo> boardFactoryInfoList = new ArrayList<>();
            if (layerTypesArr != null) {
                List<BoardCompanyData> dataList = new ArrayList<>();
                for (int i = 0; i < layerTypesArr.length; i++) {
                    BoardCompanyData boardCompanyData = new BoardCompanyData();
                    String layerType = layerTypesArr[i].trim();
                    Integer sumLayer = 0;
                    Map<String, Integer> factoryMap = new HashMap<>();
                    for (int m = 0; m < list.size(); m++) {
                        Integer layerB = StringUtils.isBlank(list.get(m).getNh3cLayersNo()) ? 0 : Integer.parseInt(list.get(m).getNh3cLayersNo());
                        String code0301 = list.get(m).getNh3cPrintbocoding().trim().toUpperCase();
                        String boardVer = list.get(m).getNh3cPcbrevision().trim().toUpperCase();
                        String boardName = list.get(m).getNh3cBoardName() == null ? "" : list.get(m).getNh3cBoardName().trim().toUpperCase();
                        String keyB = code0301 + "-" + boardVer;
                        if (map.containsKey(keyB) && map.get(keyB)!=null && map.get(keyB)!=0) {
                            layerB = map.get(keyB);
                        }
                        if (map2.containsKey(keyB)) {
                            boardName = map2.get(keyB);
                        }
                        if (layerType.contains("~")) {
                            if (layerType.indexOf("~") == layerType.length() - 1) //20~
                            {
                                Integer layer = Integer.parseInt(layerType.substring(0, layerType.length() - 1));
                                if (layerB >= layer) {
                                    BoardFactoryInfo boardFactoryInfo = new BoardFactoryInfo();
                                    boardFactoryInfo.setCode0301(code0301);
                                    boardFactoryInfo.setVersion0301(boardVer);
                                    boardFactoryInfo.setLayer(layerB);
                                    boardFactoryInfo.setCompanyName(list.get(m).getNh3cForeignassman().trim().toUpperCase());
                                    boardFactoryInfo.setNh3cBoTime(list.get(m).getNh3cBoTime());
                                    boardFactoryInfo.setProductBoardName(boardName);
                                    boardFactoryInfo.setQty(1);
                                    boardFactoryInfoList.add(boardFactoryInfo);
                                }
                            } else if (layerType.indexOf("~") == 0)//~20
                            {
                                Integer layer = Integer.parseInt(layerType.substring(1));
                                if (layerB <= layer) {
                                    BoardFactoryInfo boardFactoryInfo = new BoardFactoryInfo();
                                    boardFactoryInfo.setCode0301(code0301);
                                    boardFactoryInfo.setVersion0301(boardVer);
                                    boardFactoryInfo.setLayer(layerB);
                                    boardFactoryInfo.setCompanyName(list.get(m).getNh3cForeignassman().trim().toUpperCase());
                                    boardFactoryInfo.setNh3cBoTime(list.get(m).getNh3cBoTime());
                                    boardFactoryInfo.setProductBoardName(boardName);
                                    boardFactoryInfo.setQty(1);
                                    boardFactoryInfoList.add(boardFactoryInfo);
                                }
                            } else {//2~10,14~18
                                Integer layer1 = Integer.parseInt(layerType.substring(0, layerType.indexOf("~")));
                                Integer layer2 = Integer.parseInt(layerType.substring(layerType.indexOf("~") + 1));
                                if (layerB >= layer1 && layerB <= layer2) {
                                    BoardFactoryInfo boardFactoryInfo = new BoardFactoryInfo();
                                    boardFactoryInfo.setCode0301(code0301);
                                    boardFactoryInfo.setVersion0301(boardVer);
                                    boardFactoryInfo.setLayer(layerB);
                                    boardFactoryInfo.setCompanyName(list.get(m).getNh3cForeignassman().trim().toUpperCase());
                                    boardFactoryInfo.setNh3cBoTime(list.get(m).getNh3cBoTime());
                                    boardFactoryInfo.setProductBoardName(boardName);
                                    boardFactoryInfo.setQty(1);
                                    boardFactoryInfoList.add(boardFactoryInfo);
                                }
                            }
                        } else { //12
                            Integer layer = Integer.parseInt(layerType);
                            if (layer == layerB) {
                                BoardFactoryInfo boardFactoryInfo = new BoardFactoryInfo();
                                boardFactoryInfo.setCode0301(code0301);
                                boardFactoryInfo.setVersion0301(boardVer);
                                boardFactoryInfo.setLayer(layerB);
                                boardFactoryInfo.setCompanyName(list.get(m).getNh3cForeignassman().trim().toUpperCase());
                                boardFactoryInfo.setNh3cBoTime(list.get(m).getNh3cBoTime());
                                boardFactoryInfo.setProductBoardName(boardName);
                                boardFactoryInfo.setQty(1);
                                boardFactoryInfoList.add(boardFactoryInfo);
                            }
                        }

                    }
                    boardCompanyData.setCompanyDataList(factoryMap);
                    boardCompanyData.setLayerType(layerType);
                    boardCompanyData.setSumQty(sumLayer);
                    dataList.add(boardCompanyData);
                }
            }
            System.out.println("t888");
            boardProportionInfoDao.deleteByType();
            for (int i = 0; i < boardFactoryInfoList.size(); i++) {
                System.out.println("i="+i);
                BoardProportionInfo boardProportionInfo = new BoardProportionInfo();
                boardProportionInfo.setCode0301(boardFactoryInfoList.get(i).getCode0301());
                boardProportionInfo.setVersion0301(boardFactoryInfoList.get(i).getVersion0301());
                boardProportionInfo.setCompanyName(boardFactoryInfoList.get(i).getCompanyName());
                boardProportionInfo.setCompanyCode(boardFactoryInfoList.get(i).getCompanyCode());
                boardProportionInfo.setLayer(boardFactoryInfoList.get(i).getLayer());
                boardProportionInfo.setNh3cBoTime(boardFactoryInfoList.get(i).getNh3cBoTime());
                boardProportionInfo.setProductBoardName(boardFactoryInfoList.get(i).getProductBoardName());
                boardProportionInfo.setQty(1);
                boardProportionInfo.setCreateTime(new Date());
                boardProportionInfo.setIsManual(2);
                boardProportionInfoDao.insert(boardProportionInfo);
            }
            System.out.println("t999");
            return  ResultUtil.tablePageSuccess(page,pageSize,boardFactoryInfoList.size(),boardFactoryInfoList,list);
        }
        catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, "异常:" + e.getCause().getMessage(), "Exception:" + e.getCause().getMessage(), null);
        }
    }


    @Override
    public Result getBoarProportion2() {
//        try{
//            AxiConfig timeRange = axiConfigDao.getByAttrName("BoarProportion_TimeRange",3);
//            AxiConfig layerTypes = axiConfigDao.getByAttrName("BoarProportion_LayerTypes",3);
//            if(timeRange == null || layerTypes == null){
//                return ResultUtil.error(500,"时间范围或者层数类型未定义",null,null);
//            }
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            if(StringUtils.isBlank(timeRange.getAttrValue()) || StringUtils.isBlank(layerTypes.getAttrValue())){
//                return ResultUtil.error(500,"时间范围或者层数类型数据未定义",null,null);
//            }
//            String[] timeRangeArr = timeRange.getAttrValue().split(",");
//            String[] layerTypesArr = layerTypes.getAttrValue().split(",");
//            Date startTime = null;
//            Date endTime = null;
//            if(timeRangeArr!=null && timeRangeArr.length>0){
//                startTime = sdf.parse(timeRangeArr[0]);
//                endTime = sdf.parse(timeRangeArr[1]);
//            }
//            PcbParentFactoryInfo search = new PcbParentFactoryInfo();
//            search.setStatus(1);
//            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoDao.getAllByLimit(search);
//            List<BoardProportion> list = boardProportionDao.getList(startTime,endTime,null);
//            String md5Sign = "6244832a706bbb2c81fb093367027f56";
//            MultipartEntityBuilder params = MultipartEntityBuilder.create();
//            params.addTextBody("signature", md5Sign);
//            String res = HttpUtil.sendPostFormData(getBoardListApi, params);
//            JSONObject jsonObjectRes = JSON.parseObject(res);//
//
//            List<BoardResult> results = new ArrayList<>();
//
//            Map<String,Object> mapRes = new HashMap<>();
//            mapRes.put("timeRange",timeRangeArr);
//            mapRes.put("layerTypes",layerTypesArr);
//            List<BoardProportionInfo> boardProportionInfoList = boardProportionInfoDao.getAll();
//            if(layerTypesArr != null) {
//                List<BoardCompanyData> dataList = new ArrayList<>();
//
//                for (int i = 0; i < layerTypesArr.length; i++) {
//                    BoardCompanyData boardCompanyData = new BoardCompanyData();
//                    String layerType = layerTypesArr[i].trim();
//                    Integer sumLayer = 0;
//                    Map<String, Integer> factoryMap = new HashMap<>();
//                    for (int mm=0;mm<boardProportionInfoList.size();mm++) {
//                        Integer layerB = boardProportionInfoList.get(mm).getLayer();
//                        String boardName = boardProportionInfoList.get(mm).getCode0301();
//                        String boardVer = boardProportionInfoList.get(mm).getVersion0301();
//                        Integer boardQty = boardProportionInfoList.get(mm).getQty();
//                        String finalBoardVer = "VER." + boardVer;
//                        if(layerB == null){
//                            continue;
//                        }
//                        if (layerType.contains("~")) {
//                            if (layerType.indexOf("~") == layerType.length() - 1) //20~
//                            {
//                                Integer layer = Integer.parseInt(layerType.substring(0, layerType.length() - 1));
//                                if (layerB >= layer){
//                                    List<BoardProportion> boardProportions = list.stream().filter(x -> boardName.equals(x.getNh3cPrintbocoding())
//                                            && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                    sumLayer = sumLayer + boardProportions.size();
//                                }
//                                for (int j = 0; j < pcbParentFactoryInfoList.size(); j++)  {
//                                    String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
//                                    if (layerB >= layer)
//                                    {
//                                        List<BoardProportion> boardProportions = list.stream().filter(x -> x.getNh3cForeignassman().trim().equals(factoryName)
//                                                &&  boardName.equals(x.getNh3cPrintbocoding())
//                                                && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                        if(boardProportions.size()>0){
//                                            if (factoryMap.containsKey(factoryName)) {
//                                                Integer qty = factoryMap.get(factoryName) + boardQty;
//                                                factoryMap.put(factoryName, qty);
//                                            }
//                                            else {
//                                                factoryMap.put(factoryName, boardQty);
//                                            }
//                                        }
//                                        else {
//                                            if (!factoryMap.containsKey(factoryName)){
//                                                factoryMap.put(factoryName, 0);
//                                            }
//                                        }
//                                    }else {
//                                        if (!factoryMap.containsKey(factoryName)){
//                                            factoryMap.put(factoryName, 0);
//                                        }
//                                    }
//                                }
//                            }
//                            else if (layerType.indexOf("~") == 0) {
//                                Integer layer = Integer.parseInt(layerType.substring(0, layerType.length() - 1));
//                                if (layerB <= layer){
////                                    sumLayer++;
//                                    List<BoardProportion> boardProportions = list.stream().filter(x -> boardName.equals(x.getNh3cPrintbocoding())
//                                            && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                    sumLayer = sumLayer + boardProportions.size();
//                                }
//                                for (int j = 0; j < pcbParentFactoryInfoList.size(); j++)  {
//                                    String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
//                                    if (layerB <= layer)
//                                    {
//                                        List<BoardProportion> boardProportions = list.stream().filter(x -> x.getNh3cForeignassman().trim().equals(factoryName)
//                                                &&  boardName.equals(x.getNh3cPrintbocoding())
//                                                && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                        if(boardProportions.size()>0){
//                                            if (factoryMap.containsKey(factoryName)) {
//                                                Integer qty = factoryMap.get(factoryName) + boardQty;
//                                                factoryMap.put(factoryName, qty);
//                                            }
//                                            else {
//                                                factoryMap.put(factoryName, boardQty);
//                                            }
//                                        }
//                                        else {
//                                            if (!factoryMap.containsKey(factoryName)){
//                                                factoryMap.put(factoryName, 0);
//                                            }
//                                        }
//                                    }else {
//                                        if (!factoryMap.containsKey(factoryName)){
//                                            factoryMap.put(factoryName, 0);
//                                        }
//                                    }
//                                }
//                            }
//                            else {//2~10,14~18
//                                Integer layer1 = Integer.parseInt(layerType.substring(0, layerType.indexOf("~")));
//                                Integer layer2 = Integer.parseInt(layerType.substring(layerType.indexOf("~") + 1));
//                                if (layerB >= layer1 && layerB <= layer2){
////                                    sumLayer++;
//                                    List<BoardProportion> boardProportions = list.stream().filter(x -> boardName.equals(x.getNh3cPrintbocoding())
//                                            && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                    sumLayer = sumLayer + boardProportions.size();
//                                }
//                                for (int j = 0; j < pcbParentFactoryInfoList.size(); j++) {
//                                    String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
//                                    if (layerB >= layer1 && layerB <= layer2)
//                                    {
//                                        List<BoardProportion> boardProportions = list.stream().filter(x -> x.getNh3cForeignassman().trim().equals(factoryName)
//                                                &&  boardName.equals(x.getNh3cPrintbocoding())
//                                                && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                        if(boardProportions.size()>0){
//                                            if (factoryMap.containsKey(factoryName)) {
//                                                Integer qty = factoryMap.get(factoryName) + boardQty;
//                                                factoryMap.put(factoryName, qty);
//                                            }
//                                            else {
//                                                factoryMap.put(factoryName, boardQty);
//                                            }
//                                        }
//                                        else {
//                                            if (!factoryMap.containsKey(factoryName)){
//                                                factoryMap.put(factoryName, 0);
//                                            }
//                                        }
//                                    }else {
//                                        if (!factoryMap.containsKey(factoryName)){
//                                            factoryMap.put(factoryName, 0);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                        else { //12
//                            Integer layer = Integer.parseInt(layerType);
//                            if (layer == layerB){
////                                sumLayer++;
//                                List<BoardProportion> boardProportions = list.stream().filter(x -> boardName.equals(x.getNh3cPrintbocoding())
//                                        && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                sumLayer = sumLayer + boardProportions.size();
//                            }
//                            for (int j = 0; j < pcbParentFactoryInfoList.size(); j++)   {
//                                String factoryName = pcbParentFactoryInfoList.get(j).getCompanyNameFull();
//                                if (layer == layerB) {
//                                    List<BoardProportion> boardProportions = list.stream().filter(x -> x.getNh3cForeignassman().trim().equals(factoryName)
//                                            &&  boardName.equals(x.getNh3cPrintbocoding())
//                                            && finalBoardVer.equals(x.getNh3cPcbrevision().toUpperCase()) ).collect(Collectors.toList());
//                                    if(boardProportions.size()>0){
//                                        if (factoryMap.containsKey(factoryName)) {
//                                            Integer qty = factoryMap.get(factoryName) + boardQty;
//                                            factoryMap.put(factoryName, qty);
//                                        }
//                                        else {
//                                            factoryMap.put(factoryName, boardQty);
//                                        }
//                                    }
//                                    else {
//                                        if (!factoryMap.containsKey(factoryName)){
//                                            factoryMap.put(factoryName, 0);
//                                        }
//                                    }
//                                }else {
//                                    if (!factoryMap.containsKey(factoryName)){
//                                        factoryMap.put(factoryName, 0);
//                                    }
//                                }
//                            }
//                        }
//
//                    }
//                    boardCompanyData.setCompanyDataList(factoryMap);
//                    boardCompanyData.setLayerType(layerType);
//                    boardCompanyData.setSumQty(sumLayer);
//                    dataList.add(boardCompanyData);
//                }
//
//                for(int i=0;i<dataList.size();i++){
//                    BoardResult boardResult = new BoardResult();
//                    boardResult.setLayerType(dataList.get(i).getLayerType()+"层");
//
//                    Integer sumQty = dataList.get(i).getSumQty();
//                    Map<String, Integer> companyDataList = dataList.get(i).getCompanyDataList();
//                    List<BoardResult.CompanyData> companyList = new ArrayList<>();
//                    for (Map.Entry<String, Integer> entry : companyDataList.entrySet()){
//                        BoardResult.CompanyData companyData = new BoardResult.CompanyData();
//                        List<PcbParentFactoryInfo> collect = pcbParentFactoryInfoList.stream().filter(x -> x.getCompanyNameFull().equals(entry.getKey())).collect(Collectors.toList());
//                        if(collect.size()>0){
//                            companyData.setCompanyCode(collect.get(0).getCompanyCode());
//                            companyData.setCompanyName(collect.get(0).getCompanyName());
//                            companyData.setCompanyNameFull(entry.getKey());
//                            final double v = entry.getValue() * 1.0 / sumQty;
//                            double number = sumQty == 0 ? 0: ((entry.getValue()*1.0/sumQty)*100);
//                            DecimalFormat df = new DecimalFormat("#.00");
//                            String formattedNumber = df.format(number);
//                            double result = Double.parseDouble(formattedNumber);
//                            companyData.setProportionValue(result+"%");
//                        }
//                        companyList.add(companyData);
//                    }
//                    boardResult.setCompanyList(companyList);
//                    results.add(boardResult);
//                }
//            }
//            mapRes.put("data",results);
//            return ResultUtil.success(mapRes);
//        }
//        catch (Exception e){
//            return ResultUtil.error(500,"异常:"+e.getMessage(),"Exception:"+e.getMessage(),null);
//        }
        return null;
    }
    @Value("${personal.config.file.file-save-url}")
    private String rootPath;
    @Override
    public Result outputBoarProportion() {
        try{
            Result result = getBoarProportion();
            if( 200 == result.getCode()){
                List<BoardResult> data = (List<BoardResult>) result.getData();
                if(data != null){
                    AxiConfig layerTypes = axiConfigDao.getByAttrName("BoarProportion_LayerTypes", 3);
                    if (layerTypes == null) {
                        return ResultUtil.error(500, "层数类型未定义", null, null);
                    }
                    String[] layerTypesArr = layerTypes.getAttrValue().split(",");
                    // 创建工作簿对象
                    Workbook workbook = new XSSFWorkbook();
                    // 创建工作表对象
                    Sheet sheet = workbook.createSheet("Sheet1");
                    Row rowT0 = sheet.createRow(0);
                    Cell cell00 = rowT0.createCell(0);
                    cell00.setCellValue("序号");
                    Cell cell01 = rowT0.createCell(1);
                    cell01.setCellValue("厂家");
                    for(int j=0; j< layerTypesArr.length; j++){
                        Cell cell0j = rowT0.createCell(j+2);
                        cell0j.setCellValue(layerTypesArr[j]+"层");
                    }
                    int rowIndex = 2;
                    for(int j=0;j<data.size();j++){
                        List<BoardResult.CompanyData> companyList = data.get(j).getCompanyList();
                        for(int i=0; i< companyList.size(); i++){
                            Row rowTi = sheet.getRow(rowIndex + i);
                            if(rowTi == null){
                                rowTi = sheet.createRow(rowIndex + i);
                                Cell celli0 = rowTi.createCell(0);
                                celli0.setCellValue( i+1 );
                                Cell celli1 = rowTi.createCell(1);
                                celli1.setCellValue( companyList.get(i).getCompanyNameFull() );
                            }
                            Cell cellij = rowTi.createCell(j+2);
                            cellij.setCellValue(companyList.get(i).getProportionValue());
                        }
                    }

                    String filename = "投板数据统计" + String.valueOf(System.currentTimeMillis());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(new Date());
                    File folder = new File(rootPath + "pcb\\" + format);
                    if (!folder.isDirectory()) {
                        folder.mkdirs();
                    }
                    String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
                    FileOutputStream outputStream = new FileOutputStream(filePath);
                    workbook.write(outputStream);
                    workbook.close();
                    outputStream.close();
                    return ResultUtil.success(filePath);
                }
                else {
                    return result;
                }
            }
            else {
                return result;
            }
        }
        catch (Exception e){
            return ResultUtil.error(500,e.getMessage(),e.getMessage(),null);
        }
    }


}
